import OSS from 'ali-oss'
import { user_getOssStsInfo } from '@/api/user'

let ossClient: any
export const ossUpload = async (files, path = 'userHead') => {
  if (!ossClient) {
    const res = await user_getOssStsInfo()
    const ossConfig = res.data
    ossClient = new OSS({
      region: ossConfig.region,
      accessKeyId: ossConfig.accessKeyId,
      accessKeySecret: ossConfig.accessKeySecret,
      stsToken: ossConfig.securityToken,
      bucket: ossConfig.bucket
    })
  }
  let result
  try {
    if (Array.isArray(files)) {
      result = []
      files.forEach(async file => {
        const fileType = file.name.split('.').pop()
        const data = await ossClient.put(`${path}/${Date.now()}.${fileType}`, file)
        result.push(data.url)
      })
    } else {
      const fileType = files.name.split('.').pop()
      const data = await ossClient.put(`${path}/${Date.now()}.${fileType}`, files)
      result = data.url
    }
  } catch (error) {
    console.log(error, 'error')
    return Promise.reject(error)
  }
  return Promise.resolve(result)
}
